﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using POCOS;
using DAL;
using GUI.Models;
using BLL;
using BLL.Interfaces;
using System.Linq.Expressions;
using System.IO;
using GUI.Models.ModelArt;
using GUI.Infrastructure;
using WebMatrix.WebData;
using GUI.Models.AdminModels;
using System.Threading;
using System.Data.Objects.DataClasses;

namespace GUI.Controllers
{
    public class ArticlesController : MyBaseCultureController
    {
        
    


        
        private AuteurContext db = new AuteurContext();
      

        private IArticlesServices _articleservices;

        List<String> culture;
        public ArticlesController(IArticlesServices articlesServices)
        {
           
            
            this._articleservices = articlesServices;
            culture = new List<String> { "عربي", "Romain" };
        }

        // GET: /Articles/


        public JsonResult GetAuthor(int Id)
        {
            var idAuthor = Convert.ToInt32(Id);
            var objAuthor = from x in db.Auteurs
                            where(x.Id==Id)
                            select (new AuteurModel
                            {
                                Id=x.Id,
                                Name=x.Name,
                                Lastname=x.Lastname,
                                Profil=x.Profil

                            });
            return Json(objAuthor, JsonRequestBehavior.AllowGet);
        }


        [Authorize]

        public ActionResult Index(string id)
        {
            string iddecodde = IntExtensions.Decode(id);
            Session["currentauthorId"] = iddecodde;
            Session["authorIdEncoded"] = IntExtensions.Encode(iddecodde);
            ViewBag.session = Session["authorIdEncoded"];

            var author = _articleservices.FindAuthor(Convert.ToInt32(Session["currentauthorId"]));
            AuteurModel model = new AuteurModel();
            model.Id = author.Id;
            model.Name = author.Name; model.Lastname = author.Lastname; model.Profil = author.Profil;
            model.Adressmail = author.Adressmail;
            ViewBag.idauth = Convert.ToInt32(Session["currentauthorId"]);
            ViewBag.author = model;
            return View();
        }
        //
        // GET: /Articles/Details/5
        // get author detail Id 
        public PartialViewResult AuthorDetail()
        {

            int authorid = Convert.ToInt32(Session["currentauthorId"]);
            var authors = db.Auteurs.Where(a => a.Id == authorid).FirstOrDefault();
            return PartialView("_AuthorDetail");
        }
        [Authorize]
        public ActionResult Details(string id)
        {
            ViewBag.id = id;
           int isdetailar = Convert.ToInt32(IntExtensions.Decode(id));
           var article = _articleservices.GetArticleById(isdetailar);
          ArticleModel model = new ArticleModel();
          
            model.Title = article.Title;
            model.CreationDate = article.CreationDate;
            model.UpdateDate = article.UpdateDate;
            model.IsActive = article.IsActive;
            model.Culture = article.Culture;
            model.ArticleContenent = article.ArticleContenent;
            ViewBag.themes = GetThemeid(isdetailar);
            //image url // ImageByte

            model.ImageUrl = article.UrlImage;
            model.ImageBytes = article.ImageBytes;

            model.ImageMedium = article.ImageMedium;
            model.ImageLittle = article.ImageLittle;


            //ViewBag
            ViewBag.imagebyte = article.ImageBytes;
            ViewBag.ImageMedium = article.ImageMedium;
            ViewBag.ImageLittle = article.ImageLittle;
            ViewBag.ImageUrl = article.UrlImage;
            ViewBag.culture = article.Culture;
            ViewBag.isactif = article.IsActive;
            ViewBag.idauthor = Session["authorIdEncoded"];



            return View(model);
        }
        [Authorize]

        public ActionResult DetailArticle(int id)
        {

            var article = _articleservices.GetArticleById(id);
            ArticleModelAdmin model = new ArticleModelAdmin();
            model.Id = article.Id;
            model.Title = article.Title;
            model.CreationDate = article.CreationDate;
            model.UpdateDate = article.UpdateDate;
            model.IsActive = article.IsActive;

            model.ArticleContenent = article.ArticleContenent;
            model.Themes = article.themes;

            //image url // ImageByte

            model.ImageUrl = article.UrlImage;
            model.ImageBytes = article.ImageBytes;

            //ViewBag
            ViewBag.imagebyte = article.ImageBytes;
            ViewBag.ImageUrl = article.UrlImage;


            return View(model);
        }

        //
        // GET: /Articles/Create
        [Authorize]
        public ActionResult Create(string set02568auId)
        {
            string IdAuhtor = IntExtensions.Decode(set02568auId);

            Session["idauthor"] = Convert.ToInt32(Session["currentauthorId"]);

            ArticleModel model = new ArticleModel();

            model.CreationDate = DateTime.Now;
          


            model.AuteurId = WebSecurity.CurrentUserId;

            //list des cultures 

            ViewBag.language = new SelectList(culture);

            ViewBag.CultureId = new SelectList(db.Articles, "Id", "Culture", model.Culture);

            //IEqualityComparer<Themes> themecomparer = new DistinctThem();
            //IEnumerable<Themes> y = db.Themes.ToList().Distinct(themecomparer);

            //List<Themes> th = new List<Themes>();
            //foreach (var item in y)
            //{
            //    Themes themitem = new Themes();
            //    themitem.Id = item.Id;
            //    themitem.Subjects = item.Subjects;
            //    th.Add(themitem);
            //}

           


            //ViewBag.Theme = th;


            ViewBag.ThemeList = GetThemeTo(null);

            return View(model);
        }





        //Temes

        public ActionResult GetThemesAutocomplete(string term)
        {
             //IEqualityComparer<Themes> themecomparer = new DistinctThem();
             //IEnumerable<Themes> result = db.Themes.ToList().Distinct(themecomparer);

             var syggestion = from s in db.Themes 
                              select s.Subjects;

             var  namelist = syggestion.Where(n => n.ToLower().StartsWith(term.ToLower()));
             return Json(namelist, JsonRequestBehavior.AllowGet);
        }




    



        public byte[] ConvertToBytes(HttpPostedFileBase Image)
        {
            byte[] imageBytes = null;
            using (var BinaryReader = new BinaryReader(Request.Files[0].InputStream))
            {
                imageBytes = BinaryReader.ReadBytes(Request.Files[0].ContentLength);
            }
            return imageBytes;
        }


     
        [HttpPost]
        public JsonResult ArticleList(int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
                Thread.Sleep(200);
                int articlcount = _articleservices.GetArticleCount();
                var articles = _articleservices.GetArticles(jtStartIndex, jtPageSize, jtSorting);

               
                //_articleServices._articleServices
                int id = WebSecurity.CurrentUserId;

               
                var result = from x in articles
                             where (x.AuteurId == id)

                             select new ArticleModel
                             {
                                 Id = x.Id,
                                 Title = x.Title,
                                 CreationDate = x.CreationDate,
                                 ArticleContenent = x.ArticleContenent,
                             
                          };

                List<ArticleModel> lm = new List<ArticleModel>();

                foreach (var item in result)
                {
                    ArticleModel m = new ArticleModel();
                    m.Id = item.Id;
                    m.Title = item.Title;
                    m.CreationDate = item.CreationDate;
                    m.ArticleContenent = item.ArticleContenent;
                    m.EncodeId =IntExtensions.Encode( item.Id.ToString());
                    lm.Add(m);
                }



                return Json(new { Result = "OK", Records = lm, TotalRecordCount = articlcount }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }


        public JsonResult ArticleListByFiter(string  date, int auteurid = 0, int jtStartIndex = 0, int jtPageSize = 0, string jtSorting = null)
        {
            try
            {
              
              
               
               
                var studentCount = _articleservices.GetArticleCountByFilter(date, auteurid);
                var articles = _articleservices.GetArticlesByFilter(date, auteurid, jtStartIndex, jtPageSize, jtSorting);

                //_articleServices._articleServices
                //_articleServices._articleServices
                int id = WebSecurity.CurrentUserId;


                var result = from x in articles
                             where (x.AuteurId == id)

                             select new ArticleModel
                             {
                                 Id = x.Id,
                                 Title = x.Title,
                                 CreationDate = x.CreationDate,
                                 ArticleContenent = x.ArticleContenent,

                             };

                List<ArticleModel> lm = new List<ArticleModel>();

                foreach (var item in result)
                {
                    ArticleModel m = new ArticleModel();
                    m.Id = item.Id;
                    m.Title = item.Title;
                    m.CreationDate = item.CreationDate;
                    m.ArticleContenent = item.ArticleContenent;
                    m.EncodeId = IntExtensions.Encode(item.Id.ToString());
                    lm.Add(m);
                }


                return Json(new { Result = "OK", Records = lm, TotalRecordCount = studentCount });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }


        }

        [HttpPost]
        public JsonResult CreateArticle(Article article)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
                }


                _articleservices.CreateArticle(article);
                return Json(new { Result = "OK", Record = article });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }


        [HttpPost]




        public JsonResult UpdateArticle(ArticleModel Model)
        {

            var article = _articleservices.GetArticleById(Model.Id);

            if (article == null)
            {
                return Json(new { Status = "Failed" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                article.Id = Model.Id;
                article.Title = Model.Title;
                article.CreationDate = Model.CreationDate;

                _articleservices.UpdateArticle(article);

                return Json(new { Result = "OK" });
            }
        }






        public JsonResult DeleteArticle(ArticleModel Model)
        {

            _articleservices.DeleteArticle(Model.Id);
            return Json(new { Result = "OK" });


        }
      

        //chosen  

        public MultiSelectList GetTheme(int articleId)
        {
            
            IEqualityComparer<Themes> themecomparer = new DistinctThem();
            IEnumerable<Themes> y = db.Themes.ToList().Where(x=>x.ArticleId==articleId).Distinct(themecomparer);

            


            var ThemeList = (from a in y
                             select (new MultiSelectThemeModel
                             {
                                 Id = a.Id,
                                 Title = a.Subjects

                             })).ToList();

            List<string> stringArra = new List<string>();
         
            foreach (var item in y)
            {
                Themes th = new Themes();
                th.Id = item.Id;
                stringArra.Add(th.Id.ToString());
            }


            return new MultiSelectList(ThemeList, "Id", "Title", stringArra);
          
            
        }
        public MultiSelectList GetThemeTo( List<string> selectedValues)
        {
            IEqualityComparer<Themes> themecomparer = new DistinctThem();
            IEnumerable<Themes> y = db.Themes.ToList().Distinct(themecomparer);
            var ThemeList = (from a in y
                             select (new MultiSelectThemeModel
                             {
                                 Id = a.Id,
                                 Title = a.Subjects

                             })).ToList();
           


            return new MultiSelectList(ThemeList, "Id", "Title", selectedValues);
        }
        [HttpPost]
    
        public ActionResult Create(ArticleModel ArticleModel, List<int> ThemeList, HttpPostedFileBase fileBigSize, HttpPostedFileBase fileMediumsize, HttpPostedFileBase fileLittlesize)
        {

            //int idauth = Convert.ToInt32(Session["idauthor"]);

            int AuthId = WebSecurity.CurrentUserId;
            ArticleModel.IsActive = false;
            ArticleModel.UpdateDate = DateTime.Now;
            ArticleModel.CreationDate = DateTime.Now;

            Article article = new Article();

            if (ModelState.IsValid)
            {
     
                if (fileBigSize != null)
                {
                    byte[] uploadFile1 = new byte[fileBigSize.InputStream.Length];
                    fileBigSize.InputStream.Read(uploadFile1, 0, uploadFile1.Length);
                    article.ImageBytes = uploadFile1;
                }

                if (fileMediumsize != null)
                {
                    byte[] uploadFile2 = new byte[fileMediumsize.InputStream.Length];
                    fileMediumsize.InputStream.Read(uploadFile2, 0, uploadFile2.Length);
                    article.ImageMedium = uploadFile2;
                }

                if (fileLittlesize != null)
                {
                    byte[] uploadFile3 = new byte[fileLittlesize.InputStream.Length];
                    fileLittlesize.InputStream.Read(uploadFile3, 0, uploadFile3.Length);
                    article.ImageLittle = uploadFile3;
                }

                article.CreationDate = DateTime.Now;
                article.UpdateDate = DateTime.Now;
                article.IsActive = false;
               
                article.ArticleContenent = ArticleModel.ArticleContenent;
                article.Culture = ArticleModel.Culture;
                article.AuteurId = AuthId;

               
                //List Of Thema checkboxes check box  and chosen boxes
                if (ThemeList != null)
                {
                    IEnumerable<Themes> themeVarieties = from item in db.Themes
                                                         where ThemeList.Contains(item.Id)
                                                         select item;
                    article.themes = themeVarieties.ToList();
                }

                _articleservices.CreateArticle(article);
               
                return RedirectToAction("Details", new { id = IntExtensions.Encode(article.Id.ToString()) });
            }
            return View(article);
        }



        [HttpGet]
        public ActionResult EditArticle(string id_article_to_edit)
        {
            string iddecodde = IntExtensions.Decode(id_article_to_edit);

            var article_to_edit = _articleservices.GetArticleById(Convert.ToInt32(iddecodde));
            //var article_to_edit = _articleservices.GetArticleById(id_article_to_edit);    


            if (article_to_edit == null)
            {
                ViewBag.error = "msg erro";
            }
            ArticleModel model = new ArticleModel();

                model.Id = article_to_edit.Id;
                model.Title = article_to_edit.Title;
                model.AuteurId = article_to_edit.AuteurId;
                model.ArticleContenent = article_to_edit.ArticleContenent;
               
                model.UpdateDate = DateTime.Now;
                model.CreationDate=article_to_edit.CreationDate;
       //image
                 model.ImageBytes = article_to_edit.ImageBytes;
                 model.ImageMedium = article_to_edit.ImageMedium;
                 model.ImageLittle = article_to_edit.ImageLittle;

                 Session["ImageBytes"] = model.ImageBytes;
                 Session["ImageMedium"] = model.ImageMedium;
                 Session["ImageLittle"] = model.ImageLittle;
            
            //list des themes 
            
               ViewBag.Themesl = GetTheme(article_to_edit.Id);
               ViewBag.authorid = Session["authorIdEncoded"];
             
                return View(model);
        }
        [HttpPost]
        public ActionResult EditArticle(ArticleModel model, List<int> ThemeList, HttpPostedFileBase fileBigSize, HttpPostedFileBase fileMediumsize, HttpPostedFileBase fileLittlesize)
       {

        Article Article = new Article();
            //big size
            if (fileBigSize == null)
           {
               byte[] uploadFile1 = Session["ImageBytes"] as Byte[]; 
               model.ImageBytes = uploadFile1;
               Article.ImageBytes = model.ImageBytes;
           }
           else
           {
               byte[] uploadFile1 = new byte[fileBigSize.InputStream.Length];
               fileBigSize.InputStream.Read(uploadFile1, 0, uploadFile1.Length);
               Article.ImageBytes = uploadFile1;
            }

            //medium size 
           if (fileMediumsize == null)
           {
               byte[] uploadFile2 = Session["ImageMedium"] as Byte[];

               model.ImageMedium = uploadFile2;
              Article.ImageMedium = model.ImageMedium;
           }
           else
           {

               byte[] uploadFile2 = new byte[fileMediumsize.InputStream.Length];
               fileMediumsize.InputStream.Read(uploadFile2, 0, uploadFile2.Length);
               Article.ImageMedium = uploadFile2;


           }

            //littel size
           if (fileLittlesize == null)
           {
               byte[] uploadFile3 = Session["ImageLittle"] as Byte[];

               model.ImageLittle = uploadFile3;
               Article.ImageLittle = model.ImageLittle;
           }
           else
           {
               byte[] uploadFile3 = new byte[fileLittlesize.InputStream.Length];
               fileLittlesize.InputStream.Read(uploadFile3, 0, uploadFile3.Length);
               Article.ImageLittle = uploadFile3;
           }


           Article.Id = model.Id;
           Article.Title = model.Title;
           Article.ArticleContenent = model.ArticleContenent;
           Article.AuteurId = WebSecurity.CurrentUserId;
           Article.CreationDate = DateTime.Now;
           Article.UpdateDate = DateTime.Now;
          
      
            if (ThemeList != null)
           {
               IEnumerable<Themes> themeVarieties = from item in db.Themes
                                                    where ThemeList.Contains(item.Id)
                                                    select item;
               Article.themes = themeVarieties.ToList();
           }


            _articleservices.UpdateArticle(Article);
            return RedirectToAction("Index", "Articles", new { id = IntExtensions.Encode(model.AuteurId.ToString()) });
        }
     
        
        public IEnumerable<Themes>  GetThemeid(int articleid)
        {
              IEqualityComparer<Themes> themecomparer = new DistinctThem();


             IEnumerable<Themes> y = db.Themes.Where(x => x.ArticleId == articleid).ToList().Distinct(themecomparer);


             return y;
        }





        public IEnumerable<Themes> ThemeList(int id)
        {
           
             IEqualityComparer<Themes> themecomparer = new DistinctThem();


             IEnumerable<Themes> y = db.Themes.Where(x => x.ArticleId == id).ToList().Distinct(themecomparer);
       
            return y;
        }




        //for the grid het themes
        [HttpPost]
        public JsonResult GetThemeList(int Id)
        {
            try
            {
                Thread.Sleep(200);

                IEqualityComparer<Themes> themecomparer = new DistinctThem();
                IEnumerable<Themes> themes = db.Themes.ToList().Where(x => x.ArticleId == Id).Distinct(themecomparer);

                return Json(new { Result = "OK", Records = themes });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }


        [HttpPost]
        public JsonResult DeleteThemes(int Id)
        {
            try
            {
                Thread.Sleep(50);
                var th = db.Themes.Find(Id);
                db.Themes.Remove(th);
                return Json(new { Result = "OK" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

        [HttpPost]
        public JsonResult Updatethemes(Themes themes)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
                }

                db.Entry(themes).State = EntityState.Modified;
                return Json(new { Result = "OK" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "ERROR", Message = ex.Message });
            }
        }

     
    }
}




//[AcceptVerbs(HttpVerbs.Post)]
//public JsonResult EditArt_icle(Article article)
//{
//    var getarticle = _articleservices.GetArticleById(article.Id);


//    if (!(article == null))
//    {
//        getarticle.Id = article.Id;
//        getarticle.Title = article.Title;
//        getarticle.CreationDate = article.CreationDate;
//        getarticle.ArticleContenent = article.ArticleContenent;


//        _articleservices.SaveArticle();

//        return Json(new { Status = "Success" }, JsonRequestBehavior.AllowGet);
//    }
//    else
//    {
//        return Json(new { Status = "FAILED" });
//    }


//}
//jQgrid
//[HttpPost]

//public JsonResult GridSave(int id, string title, string ArticleContenent)
//{
//    AuteurContext db = new AuteurContext();

//    Article a = db.Articles.SingleOrDefault(p => p.Id == id);




//    if (!(a == null))
//    {
//        a.Id = id;
//        a.Title = title;

//        a.ArticleContenent = ArticleContenent;

//        db.SaveChanges();
//        return Json(new { Status = "Success" }, JsonRequestBehavior.AllowGet);
//    }
//    else
//    {
//        return Json(new { Status = "Failed" });
//    }
//}



//[HttpPost]
//public ActionResult LoadjqData(string sidx, string sord, int page, int rows,
//       bool _search, string searchField, string searchOper, string searchString)
//{
//    // Get the list of students
//    int idAuthor = Convert.ToInt32(Session["currentauthorId"]);

//    var articles = _articleservices.GetArticle().Where(au => au.AuteurId == idAuthor).AsQueryable();

//    // If search, filter the list against the search condition.
//    // Only "contains" search is implemented here.
//    var filteredStudents = articles;
//    if (_search)
//    {
//        filteredStudents = articles.Where(s =>
//            (typeof(Article).GetProperty(searchField).GetValue(s, null) == null) ? false :
//                typeof(Article).GetProperty(searchField).GetValue(s, null)
//                .ToString().Contains(searchString));
//    }

//    // Sort the student list
//    var sortedStudents = SortIQueryable<Article>(filteredStudents, sidx, sord);

//    // Calculate the total number of pages
//    var totalRecords = filteredStudents.Count();
//    var totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);

//    // Prepare the data to fit the requirement of jQGrid
//    var data = (from s in sortedStudents
//                select new
//                {
//                    id = s.Id,
//                    cell = new object[] { s.Id, s.Title,s.CreationDate.ToString("MM/dd/yyyy"),
//                    s.ArticleContenent  }
//                }).ToArray();

//    // Send the data to the jQGrid
//    var jsonData = new
//    {
//        total = totalPages,
//        page = page,
//        records = totalRecords,
//        rows = data.Skip((page - 1) * rows).Take(rows)
//    };

//    return Json(jsonData);
//}

//// Utility method to sort IQueryable given a field name as "string"
//// May consider to put in a cental place to be shared
//private IQueryable<T> SortIQueryable<T>(IQueryable<T> data, string fieldName, string sortOrder)
//{
//    if (string.IsNullOrWhiteSpace(fieldName)) return data;
//    if (string.IsNullOrWhiteSpace(sortOrder)) return data;

//    var param = Expression.Parameter(typeof(T), "i");
//    Expression conversion = Expression.Convert(Expression.Property(param, fieldName), typeof(object));
//    var mySortExpression = Expression.Lambda<Func<T, object>>(conversion, param);

//    return (sortOrder == "desc") ? data.OrderByDescending(mySortExpression)
//        : data.OrderBy(mySortExpression);
//}

//protected override void Dispose(bool disposing)
//{
//    db.Dispose();
//    base.Dispose(disposing);
//}





////theme



//public ActionResult GetModelArticle(int articleId)
//{
//    ArticleResult modelResult = new ArticleResult();
//    modelResult.ModelArticle.AuteurId = Convert.ToInt32(Session["currentauthorId"]);

//    return View(modelResult);
//}

//[HttpPost]
//public ActionResult GetModelArticle(ArticleResult modelResult)
//{

//    Article article = new Article();
//    Themes theme = new Themes();
//    modelResult.ModelArticle.IsActive = false;
//    modelResult.ModelArticle.AuteurId = Convert.ToInt32(Session["currentauthorId"]);



//    modelResult.ModelArticle.CreationDate = DateTime.Now;
//    if (ModelState.IsValid)
//    {

//        article.Id = modelResult.ModelArticle.Id;
//        article.CreationDate = (DateTime)modelResult.ModelArticle.CreationDate;


//        article.ArticleContenent = modelResult.ModelArticle.ArticleContenent;
//        article.Auteur = modelResult.ModelArticle.Auteur;
//        article.AuteurId = modelResult.ModelArticle.AuteurId;



//        _articleservices.CreateArticle(article);



//        theme.ArticleId = article.Id;
//        theme.Id = modelResult.ModelTheme.Id;
//        theme.Subjects = modelResult.ModelTheme.Subjects;
//        db.Themes.Add(theme);
//        //image upload 


//        return RedirectToAction("Details", new { id = article.Id });



//    }
//    return View(article);

//}







//Jtable Grid 